package cn.edu.sdjzu.xg.eagle.dao.mapper;

import cn.edu.sdjzu.xg.eagle.dao.CommonDao;
import cn.edu.sdjzu.xg.eagle.util.Condition;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author TG.SI@188.COM
 * @version 1.0
 * 19th Oct. 2020
 * 一般性的Data Assess操作
 */
public  class CommonDaoImpl implements CommonDao {
    /**
     * 返回指定表的元素数量
     * @param connection
     * @param tableName 表名
     * @return 元组数量
     * @throws SQLException
     */
    public int count(Connection connection, String tableName) throws SQLException {
        String sql_count = "SELECT COUNT(id) as cnt FROM " + tableName;

        PreparedStatement pstmt_count =
                connection.prepareStatement(sql_count);
        int counter = 0;
        ResultSet resultSet_count = pstmt_count.executeQuery();

        if (resultSet_count.next()) {
            counter = resultSet_count.getInt("cnt");
        }
        JdbcHelper.close(resultSet_count, pstmt_count);
        return counter;
    }
    /**
     * 返回指定表的元素数量
     * @param connection
     * @param tableName 表名
     * @param conditionList 条件
     * @return 元组数量
     * @throws SQLException
     */
    public int count(Connection connection, String tableName, List<Condition> conditionList) throws SQLException {
        StringBuilder sql_count = new StringBuilder("SELECT COUNT(id) as cnt FROM " + tableName);

        //如果有条件，则生成条件子句，并附加到主语句后面
        if (conditionList != null) {
            String whereClause = Condition.toWhereClause(conditionList);
            sql_count.append(whereClause);
        }
        PreparedStatement pstmt_count =
                connection.prepareStatement(sql_count.toString());
        int counter = 0;
        ResultSet resultSet_count = pstmt_count.executeQuery();

        if (resultSet_count.next()) {
            counter = resultSet_count.getInt("cnt");
        }
        JdbcHelper.close(resultSet_count, pstmt_count);
        return counter;
    }
}
